package com.fast.orm.utils;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.fast.orm.config.FastAttributes;
import com.fast.orm.data.DataPackage;

import java.util.Date;
import java.util.Map;

public class FastValueUtil {


    public static void setUpdateBeanValue(DataPackage dataPackage, Object bean){
        if (bean!=null) {
            Map<String, Object> beanMap = BeanUtil.beanToMap(bean, false, true);
            for (String name : beanMap.keySet()) {
                dataPackage.getUpdateFieldMap().put(name,new DataPackage.UpdateField(name,beanMap.get(name), DataPackage.UpdateField.UpdateType.EQUAL));
            }
        }
    }

    public static void setInsertData(DataPackage dataPackage) {
        if (FastAttributes.isAutoSetCreateTime && dataPackage.getTableMapper().getAutoSetCreateTime()) {
            for (Object in : dataPackage.getInsertList()) {
                Date date = new Date();
                if (dataPackage.getTableMapper().getAutoSetCreateTime()){
                    Object fieldCreateTimeValue = BeanUtil.getFieldValue(in, FastAttributes.createTimeFieldName);
                    if (fieldCreateTimeValue == null) {
                        BeanUtil.setFieldValue(in, FastAttributes.createTimeFieldName, date);
                    }
                }
                if (dataPackage.getLogicDelete()&&dataPackage.getTableMapper().getLogicDelete()) {
                    BeanUtil.setFieldValue(in, FastAttributes.deleteFieldName, !FastAttributes.defaultDeleteValue);
                }
                if (dataPackage.getTableMapper().getAutoSetUpdateTime()) {
                    Object fieldUpdateTimeValue = BeanUtil.getFieldValue(in, FastAttributes.updateTimeFieldName);
                    if (fieldUpdateTimeValue == null) {
                        BeanUtil.setFieldValue(in, FastAttributes.updateTimeFieldName, date);
                    }
                }
            }
        }
    }

    public static void setUpdateTime(DataPackage dataPackage,Date date) {
        if (dataPackage.getTableMapper().getAutoSetUpdateTime()) {
            DataPackage.UpdateField updateField = dataPackage.getUpdateFieldMap().get(FastAttributes.updateTimeFieldName);
            if (updateField == null) {
                dataPackage.getUpdateFieldMap().put(FastAttributes.updateTimeFieldName
                        , new DataPackage.UpdateField(FastAttributes.updateTimeFieldName, date, DataPackage.UpdateField.UpdateType.EQUAL));
            }
        }
    }


    /**
     * 驼峰转换
     * 例如：hello_world=》helloWorld
     *
     * @param val 需要转换的值
     * @return 转换后的值
     */
    public static String toCamelCase(String val) {
        if (val == null) {
            return null;
        }
        if (FastAttributes.isToCamelCase) {
            val = StrUtil.toCamelCase(val);
        }
        return val;
    }


}
